package com.thethinkfactory.whosappfor.model;

import java.util.ArrayList;
import java.util.List;

import com.thethinkfactory.whosappfor.model.db.MySQLiteHelper;
import com.thethinkfactory.whosappfor.model.db.TableEvent;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class WhatsAppForDataSource {

	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;

	public WhatsAppForDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		database.close();
	}

	public Event createEvent(String title, String description) {
		Log.i(WhatsAppForDataSource.class.getSimpleName(), "creating event");
		ContentValues values = new ContentValues();
		values.put(TableEvent.COLUMN_TITLE, title);
		values.put(TableEvent.COLUMN_DESC, description);

		long id = database.insert(TableEvent.TABLE_NAME, null, values);

		Log.i(WhatsAppForDataSource.class.getSimpleName(), "event created");

		Cursor c = database.query(TableEvent.TABLE_NAME,
				TableEvent.ALL_COLUMNS, TableEvent.COLUMN_ID + " = " + id,
				null, null, null, null);

		Log.i(WhatsAppForDataSource.class.getSimpleName(), "cursor retrieved");

		c.moveToFirst();

		Event event = cursorToEvent(c);
		c.close();
		Log.i(WhatsAppForDataSource.class.getSimpleName(), "event parsed");
		return event;
	}

	public void deleteAllEvents() {
		database.delete(TableEvent.TABLE_NAME, null, null);
	}

	public List<Event> getAllEvents() {
		List<Event> events = new ArrayList<Event>();

		Cursor c = database.query(TableEvent.TABLE_NAME,
				TableEvent.ALL_COLUMNS, null, null, null, null, null);

		c.moveToFirst();
		while (!c.isAfterLast()) {
			Event event = cursorToEvent(c);
			events.add(event);
			c.moveToNext();
		}
		c.close();
		return events;
	}

	public Cursor getCursorAllEvents() {
		
		return database.query(TableEvent.TABLE_NAME, TableEvent.ALL_COLUMNS,
				null, null, null, null, null);
	}

	private Event cursorToEvent(Cursor c) {
		Event event = new Event();

		event.setId(c.getLong(0));
		event.setTitle(c.getString(1));
		event.setDescription(c.getString(2));

		return event;
	}

}
